package com.authsphere.springboot.starter.plugin.account.lock;

import com.authsphere.plugin.api.AuthSphereBeforePlugin;
import com.authsphere.security.account.api.lock.AccountLockBeforePlugin;
import com.authsphere.security.account.api.lock.AccountLockoutService;
import com.authsphere.security.account.api.lock.LockoutRepository;
import com.authsphere.security.account.common.config.SecurityAccountConfig;
import com.authsphere.security.account.common.lock.DefaultAccountLockoutService;
import com.authsphere.security.account.redis.lock.RedisLockoutRepository;
import com.authsphere.springboot.starter.plugin.account.AccountPluginConfiguration;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/26 09:16
 **/
@Configuration
@AutoConfigureAfter(AccountPluginConfiguration.class)
public class AccountLockoutBeforePluginConfiguration {

    @Bean
    public AuthSphereBeforePlugin authSphereBeforePlugin(final AccountLockoutService accountLockoutService) {
        return new AccountLockBeforePlugin(accountLockoutService);
    }

    @Bean
    public AccountLockoutService defaultAccountLockoutService(
            ObjectProvider<SecurityAccountConfig> provider,
            final LockoutRepository lockoutRepository) {
        SecurityAccountConfig config = provider.getIfAvailable(SecurityAccountConfig::new);
        return new DefaultAccountLockoutService(config.getLockAccountConfig(), lockoutRepository);
    }

    @Bean
    @ConditionalOnBean(StringRedisTemplate.class)
    public LockoutRepository lockoutRepository(
            ObjectProvider<SecurityAccountConfig> provider,
            final StringRedisTemplate stringRedisTemplate) {
        SecurityAccountConfig config = provider.getIfAvailable(SecurityAccountConfig::new);
        return new RedisLockoutRepository(config.getLockAccountConfig(), stringRedisTemplate);
    }
}
